package com.example.social.screen

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import coil.compose.AsyncImage
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import com.example.social.R
import com.example.social.navigation.Routes
import com.example.social.utils.PostStatus
import com.example.social.utils.SharedPref
import com.example.social.viewmodel.AddThreadViewModel

@Composable
fun AddThreads(navHostController: NavHostController) {
    val threadModel:AddThreadViewModel = viewModel()
    val postStatus by threadModel.postStatus.observeAsState(PostStatus.Idle)


    val context = LocalContext.current

    var thread by remember {
        mutableStateOf("")
    }

    var imageUri by remember {
        mutableStateOf<Uri?>(null)
    }

    var uid = SharedPref.getUid(context);
    val permissionToRequest = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        Manifest.permission.READ_MEDIA_IMAGES
    } else Manifest.permission.READ_EXTERNAL_STORAGE

    val launcher =
        rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
            imageUri = uri
        }

    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {

        } else {

        }
    }

    // LaunchedEffect 监听状态变化
    LaunchedEffect(postStatus) {
        when (postStatus) {
            is PostStatus.Complete -> {
                val success = (postStatus as PostStatus.Complete).success
                if (success) {
                    // 发布成功
                    thread = ""
                    imageUri = null
                    Toast.makeText(context, "发布成功!", Toast.LENGTH_SHORT).show()
                    navHostController.navigate(Routes.Home.routes) {
                        popUpTo(Routes.AddThreads.routes) { inclusive = true }
                    }
                } else {
                    // 发布失败
                    Toast.makeText(context, "发布失败!", Toast.LENGTH_SHORT).show()
                }
                // 重置状态，防止重复触发
                threadModel.resetPostStatus()
            }
            is PostStatus.Posting -> {
                // 显示加载指示器或禁用按钮
            }
            else -> {} // Idle 状态，无操作
        }
    }
    ConstraintLayout(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)

    ) {
        val (crossPic, text, logo, userName, replyText, button, image, editText, attachMedia, imageBox) = createRefs()
        Image(
            painter = painterResource(id = R.drawable.baseline_close_24),
            contentDescription = "close",
            modifier = Modifier
                .constrainAs(crossPic) {
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                }
                .clickable {
                    navHostController.navigate(Routes.Home.routes) {
                        popUpTo(Routes.AddThreads.routes) {
                            inclusive = true
                        }
                    }
                })
        Text(
            text = "添加话题",
            style = TextStyle(
                fontWeight = FontWeight.ExtraBold,
                fontSize = 24.sp
            ),
            modifier = Modifier.constrainAs(text) {
                top.linkTo(crossPic.top)
                start.linkTo(crossPic.end, margin = 12.dp)
                bottom.linkTo(crossPic.bottom)
            }
        )
        AsyncImage(
            model = ImageRequest.Builder(context)
                .data(SharedPref.getImageUrl(context))
                .crossfade(true)
                .error(R.drawable.undraw_male_avatar)
                .build(),
            contentDescription = "close",
            modifier = Modifier
                .constrainAs(logo) {
                    top.linkTo(text.bottom)
                    start.linkTo(parent.start)
                }
                .padding(10.dp)
                .size(33.dp)
                .clip(CircleShape),
            contentScale = ContentScale.Crop
        )
        Text(
            text = SharedPref.getName(context),
            style = TextStyle(
                fontSize = 20.sp
            ),
            modifier = Modifier
                .constrainAs(userName) {
                    top.linkTo(text.bottom, margin = 5.dp)
                    start.linkTo(logo.end, margin = 12.dp)
                }
                .padding(10.dp)
        )

        BasicTextFieldWithHint(
            hint = "将你的奇思妙想写在这里...",
            value = thread,
            onValueChange = { thread = it },
            modifier = Modifier
                .constrainAs(editText) {
                    top.linkTo(logo.bottom)
                    start.linkTo(parent.start)
                }
                .padding(horizontal = 1.dp, vertical = 10.dp,)
                .fillMaxWidth()
        )

        if (imageUri == null) {
            Image(
                painter = painterResource(id = R.drawable.baseline_attachment_24),
                contentDescription = "close",
                modifier = Modifier
                    .constrainAs(attachMedia) {
                        top.linkTo(editText.bottom)
                        start.linkTo(editText.start)
                    }
                    .clickable {
                        val isGranted = ContextCompat.checkSelfPermission(
                            context, permissionToRequest
                        ) == PackageManager.PERMISSION_GRANTED

                        if (isGranted) {
                            launcher.launch("image/*")
                        } else {
                            permissionLauncher.launch(permissionToRequest)
                        }
                    })
        } else {
            Box(modifier = Modifier
                .background(Color.Gray)
                .padding(1.dp)
                .constrainAs(imageBox) {
                    top.linkTo(editText.bottom)
                    start.linkTo(editText.start)
                    end.linkTo(parent.end)
                }
                .height(250.dp)) {
                Image(
                    painter = rememberAsyncImagePainter(model = imageUri),
                    contentDescription = "close",
                    modifier = Modifier
                        .fillMaxWidth()
                        .fillMaxSize(),
                    contentScale = ContentScale.FillBounds
                )

                Icon(
                    imageVector = Icons.Default.Close,
                    contentDescription = "移除图片",
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .clickable {
                            imageUri = null
                        })
            }
        }

                Text(
                    text = "任何人都能回复",
                    style = TextStyle(
                        fontSize = 20.sp
                    ),
                    modifier = Modifier.constrainAs(replyText) {
                        start.linkTo(parent.start, margin = 12.dp)
                        bottom.linkTo(parent.bottom, margin = 12.dp)
                    }
                )
                TextButton(onClick = {
                        threadModel.submitThread(thread,uid,imageUri,context)
                }, modifier = Modifier.constrainAs(button){
                    end.linkTo(parent.end)
                    bottom.linkTo(parent.bottom)

                }) {
                    Text(
                        text = "发布",
                        style = TextStyle(
                            fontSize = 20.sp
                        ),
                    )
                }

    }
}

@Composable
fun BasicTextFieldWithHint(
    hint: String,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier
) {
    Box(modifier = modifier) {
        if (value.isEmpty()) {
            Text(text = hint, color = Color.Gray)
        }
        BasicTextField(
            value = value,
            onValueChange = onValueChange,
            textStyle = TextStyle.Default.copy(color = Color.Black),
            modifier = Modifier.fillMaxWidth()
        )


    }
}


@Preview
@Composable
fun AddThreadsPreview() {
    val rememberNavController = rememberNavController()
    AddThreads(rememberNavController)
}